package com.lrkj.weixin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.util.SignUtils;
import com.lrkj.common.core.domain.AjaxResult;
import com.lrkj.common.utils.DateUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.weixin.config.WxPayConfiguration;
import com.lrkj.weixin.entity.WxOrderRecord;
import com.lrkj.weixin.entity.vo.BackInfoVo;
import com.lrkj.weixin.entity.vo.PayInfoVo;
import com.lrkj.weixin.entity.vo.WxBackInfoVo;
import com.lrkj.weixin.mapper.WxOrderRecordMapper;
import com.lrkj.weixin.service.WxPaymentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huxy
 * @version V1.0
 * @创建时间
 * @备注
 * @类名
 * @节点
 */
@Service
public class IWxPaymentService extends ServiceImpl<WxOrderRecordMapper, WxOrderRecord> implements WxPaymentService {

    @Override
    public AjaxResult placeOrder(PayInfoVo payInfoVo) {
        String nonceStr = StringUtils.getCode("nonce_str");
        WxPayUnifiedOrderRequest wxPayRequest = WxPayUnifiedOrderRequest.newBuilder()
                //todo 测试 1分
                .totalFee(1)
                //.totalFee(StringUtils.getAmount(payInfoVo.getOrderPrice())
                .outTradeNo(nonceStr)
                .body(payInfoVo.getOrderIntroduce())
                .openid(payInfoVo.getOrderBy())
                .spbillCreateIp(payInfoVo.getIp())
                .tradeType("JSAPI")
                .notifyUrl(WxPayConfiguration.getPayService().getConfig().getNotifyUrl())
                .build();
        try {
            WxPayUnifiedOrderResult back = WxPayConfiguration.getPayService().unifiedOrder(wxPayRequest);
            if (!StringUtils.isEmpty(back.getResultCode())) {
                Map<String, String> paySignInfo = new HashMap<>();
                String timeStamp = DateUtils.getTimeWW(0);
                paySignInfo.put("appId", WxPayConfiguration.getPayService().getConfig().getAppId());
                paySignInfo.put("nonceStr", nonceStr);
                paySignInfo.put("timeStamp", timeStamp);
                paySignInfo.put("signType", "MD5");
                paySignInfo.put("package", "prepay_id=" + back.getPrepayId());
                String paySign = SignUtils.createSign(paySignInfo, "MD5", WxPayConfiguration.getPayService().getConfig().getMchId(), new String[]{});
                //组合支付参数
                WxOrderRecord wxOrderRecord = new WxOrderRecord();
                BeanUtils.copyProperties(payInfoVo, wxOrderRecord);
                wxOrderRecord.setOrderId(nonceStr);
                wxOrderRecord.setOrderCount(1);
                wxOrderRecord.setOrderState(0);
                wxOrderRecord.setOrderTime(DateUtils.getNowDate());
                wxOrderRecord.setTimeStamp(timeStamp);
                wxOrderRecord.setOrderRes(WxPayConfiguration.getPayService().getConfig().getAppId());
                BackInfoVo backInfoVo = new BackInfoVo();
                BeanUtils.copyProperties(wxOrderRecord, backInfoVo);
                backInfoVo.setPackageInfo("prepay_id=" + back.getPrepayId());
                backInfoVo.setSignType("MD5");
                backInfoVo.setPaySign(paySign);
                saveRecord(wxOrderRecord);
                return AjaxResult.success(backInfoVo);

            }
        } catch (WxPayException e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.error();
    }

    /**
     * @author huxy
     * @创建时间 2022/8/31 11:10 AM
     * @备注
     * @节点
     */
    public void saveRecord(WxOrderRecord wxOrderRecord) {
        this.save(wxOrderRecord);
    }

    public WxBackInfoVo payBack(String msg) {
        WxBackInfoVo wxBackInfoVo = new WxBackInfoVo();
        wxBackInfoVo.setOk(false);
        try {
            WxPayOrderNotifyResult notifyResult = WxPayConfiguration.getPayService().parseOrderNotifyResult(msg);
            List<WxOrderRecord> list = (List<WxOrderRecord>) this.lambdaQuery().eq(WxOrderRecord::getOrderId, notifyResult.getOutTradeNo());
            if (list.size() > 0) {
                WxOrderRecord record = list.get(0);
                record.setOverTime(DateUtils.getNowDate());
                record.setOrderState(1);
                this.updateById(record);
                wxBackInfoVo.setParameterList(record.getParameterList());
                wxBackInfoVo.setOk(true);
                wxBackInfoVo.setWxOrderRecord(record);
                wxBackInfoVo.setWxBack(WxPayNotifyResponse.success("回调成功！"));
            }
        } catch (WxPayException e) {
            wxBackInfoVo.setWxBack(WxPayNotifyResponse.fail("回调有误!"));
            e.printStackTrace();
        }
        return wxBackInfoVo;
    }

    @Override
    public List<WxOrderRecord> indexShow(String time) {
        QueryWrapper<WxOrderRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("sum(order_price*order_count) as orderPrice,order_state orderState");
        queryWrapper.eq("DATE_FORMAT(order_time,'%Y-%m-%d')", time);
        queryWrapper.groupBy("order_state");
        return list(queryWrapper);
    }
}
